$(function(){
    // 初始化表格数据
    var am_table = $('#example').DataTable({
        "dom": '<"top">rt<"bottom"ip><"clear">',
        "ajax": {
            "url":SERVICE_URL + "/listAgency",
            // "url": "/AfterSaleService/js/jsonData/maintenance_account.json",
            "data":{type:0},
            "dataSrc": "data"
        },
        "createdRow": function (row, data, index) {
            console.log(index);
        },
        "columns": [
            { "data": "name" },
            { "data": "phone" },
            {
                "render": function (data, type, full, meta) {// edit-btn data-am-modal="{target: \'#am_modal_user\'}" onclick="openEditModal(this)"
                    return '<button type="button" class="am-btn am-btn-default purple edit-btn">修改</button>';
                },
                "class": "center"
            },
        ],
        "ordering": false,
    });
    //前台添加序号
    // am_table.on('order.dt search.dt',
    // function() {
    //     am_table.column(0, {
    //         "search": 'applied',
    //         "order": 'applied'
    //     }).nodes().each(function(cell, i) {
    //         cell.innerHTML = i + 1;
    //     });
    // }).draw();
    $('#add-user').on('click', function(){
        $('#form-data')[0].reset();
        $('#am_modal_user').modal('open');
    });

    $("#example tbody").on("click",".edit-btn",function(){
        var tds=$(this).parents("tr").children();
        $.each(tds, function(i,val){
            var jqob=$(val);
            if(jqob.has('button').length ){return true;}//跳过第1项 序号,按钮
            var txt=jqob.text();
            var put=$("<input type='text' style='width: 100%;'>");
            put.val(txt);
            jqob.html(put);
        });
        $(this).before('<button class="am-btn purple cancle-btn">取消</button>');
        $(this).html("保存");
        $(this).toggleClass("edit-btn");
        $(this).toggleClass("save-btn");
    });

    $("#example tbody").on("click",".save-btn",function(){
        var that = this;
        var row=am_table.row($(this).parents("tr"));
        var tds=$(this).parents("tr").children();
        $.each(tds, function(i,val){
            var jqob=$(val);
            //把input变为字符串
            if(!jqob.has('button').length){
                var txt=jqob.children("input").val();
                jqob.html(txt);
                am_table.cell(jqob).data(txt);//修改DataTables对象的数据
            }
        });
        var data=row.data();
        Server.postToManage('/saveVendor', {data: JSON.stringify(data)}, function(result){
            console.log(result);
            if(result.msg === 'success'){
                alert('修改成功!');
                $(that).html("修改");
                $('.cancle-btn').remove();
                $(that).toggleClass("edit-btn");
                $(that).toggleClass("save-btn");
            }else{
                alert('修改失败，请稍后重试！');
            }
        });
    });

    $("#example tbody").on("click",".cancle-btn",function(){
        let tr = $(this).parents("tr");
        let rowData = am_table.row(tr).data();
        
        let tds=tr.children();
        $.each(tds, function(i,val){
            let jqob=$(val);
            //把input变为字符串
            if(!jqob.has('button').length){
                switch(i){
                    case 0:jqob.html(rowData.name);break;
                    case 1:jqob.html(rowData.phone);break;
                    default:;
                }
            }
        });
        $(this).remove();
        $('.save-btn').html("修改").addClass('edit-btn').removeClass('save-btn');
    });
});
//生成二维码
function creatCode() {
	var name = $.trim($("#name").val());
	var phone = $.trim($("#phone").val());
	if(name == "" || phone == "") {
		alert("请输入姓名和电话!");
		return false;
	}

	Server.postToUser("/isExistPhone", {
		"phone": phone,
		"flag":AGENCY_USER
	}, function(result) {
		if(result) {
			alert("号码已存在!");
			return false;
		} else {
			var obj = new WxLogin({
				self_redirect: true,
				id: "wx_code",
				appid: "wxb90d59ffb6e50089",
				scope: "snsapi_login",
				redirect_uri: encodeURIComponent("http://open-family.wdiplumbing.com/openuser/loginWebCallback"),
				state: phone+","+AGENCY_USER,
				style: "black",
				href: "",
			});
			$(".am-hide").removeClass("am-hide");
		}
		console.log(result);
	})
}
/**
 * 保存弹框表单数据
 */
function saveUser(){
    var data = {};
    let empty = false;
    $('input','#form-data').each((index,elem) => {
        if(!elem.value){
            empty = true;
            return false;
        }
        if(elem.id != null){
            data[elem.id] = elem.value;
        }
    });
    if(empty){
        alert("不能有空值");
        return false;
    }
    Server.postToManage('/saveVendor', {data: JSON.stringify(data)}, function(result){
        console.log(result);
        if(result.msg === 'success'){
            alert('增加成功!');
            var table = $('#example').DataTable();
            data.id = result.data;
            table.row.add(data).draw();
            $('#am_modal_user').modal('close');
        }else{
            alert('增加失败，请稍后重试！');
        }
    });
};


/**
 * 打开修改弹框
 * @param {*} obj 
 */
function openEditModal(obj) {
    //打开弹框时，清空表单
    $('#form-data')[0].reset();
    //获取点击行元素DOM
    var rowObj = obj.parentNode.parentNode;
    //获取表格实例
    var table = $('#example').DataTable();
    //获取行数据
    var data = table.row(rowObj).data();
    //获取表单元素，并根据id赋值
    $('input', '#form-data').each((index,elem) => {
       if(elem.id){
           elem.value = data[elem.id];
       }
    });
    // $('#registerDate').datepicker('setValue', data.registerDate);
}
/**
 * 重置密码
 * @param {DOM} obj 
 */
function resetPwd(obj){
    //获取点击行元素DOM
    var rowObj = obj.parentNode.parentNode;
    //获取表格实例
    var table = $('#example').DataTable();
    //获取行数据
    var data = table.row(rowObj).data();
    console.log(data.id);
    
    if(data.id === undefined){
        alert('请刷新后重试！');
        return false;
    }
    Server.postToManage('/resetPwd', {id: data.id, tel: data.tel}, function(res){
        if(res.msg === 'success'){
            alert('重置成功，短信已发送！');
        }else{
            alert("重置失败，请稍后重试！");
        }
    });
}